import datetime
import random
import time

from event_publisher import *
from event_subscriber import subscribe_event


class MyConsumer1:
    """
    消费者 1
    """

    def consume(self, message):
        """
        接收消息，消息体可以是任意类型
        :param message:
        :return:
        """
        print(f"MyConsumer1: {message.code} {message.data}")


class MyConsumer2:
    """
    消费者 2
    """

    def on_message(self, message):
        print(f"MyConsumer2: {message.code} {message.data}")


cs1 = MyConsumer1()
subscribe_event("topic 1", cs1.consume)  # 消费者1订阅主题"1"
cs2 = MyConsumer2()
subscribe_event("topic 2", cs2.on_message)  # 消费者2订阅主题"2"

while True:
    time.sleep(1)
    r = random.randint(1, 2)  # 随机生成1或2，作为主题
    # 下面发布消息到指定的主题topic r
    publish_event(Message("topic - " + str(r), r, f"hello {datetime.datetime.now()}"))
